import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_getx/app/data/api/api.dart';
import 'package:flutter_getx/app/service/db_service.dart';
import 'package:flutter_getx/app/service/dio_service.dart';
import 'package:flutter_getx/app/service/local_storage_service.dart';
import 'package:flutter_getx/app/service/message_service.dart';
import 'package:flutter_getx/app/service/user_info_service.dart';
import 'package:flutter_getx/app/util/dio/app_response.dart';
import 'package:get/get.dart';

import '../../../data/model/uer_info.dart';
import '../../../routes/app_pages.dart';

class LoginController extends GetxController {
  TextEditingController accountTec = new TextEditingController();
  TextEditingController pwdTec = new TextEditingController();

  DioService dioService = Get.find();
  UserInfoService userInfoService = Get.find();
  MessageService messageService = Get.find();
  LocalStorageService localStorageService = Get.find();
  DBService dbService = Get.find();

  Api api = new Api();

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {}

  Future<void> login() async {
    var phone = accountTec.text;
    var pwd = pwdTec.text;

    var encodePwd = md5.convert(utf8.encode(pwd)).toString();
    print("pwd:******" + encodePwd);

    AppResponse response = await dioService
        .post("/user/login", data: {"phone": phone, "password": encodePwd});
    if (response.ok) {
      userInfoService.userInfo.value = UserInfo.fromJson(response.data);
      localStorageService.setData(localStorageService.userInfoKey,
          userInfoService.userInfo.value.toJson());

      await messageService.infoSync();

      // 重新加载消息服务
      // messageService.connect();
      EasyLoading.showSuccess("登录成功");
      Get.offNamed(Routes.HOME);
    }
  }
}
